<?php
exists_frame();
class libtemplate {
    public $_var = null;
    public $cfg = array();
    public $ajx_return_data = null;
    public $T = null;
    public function __construct($cfg) {
        $this->cfg = $cfg;
    }
    public function display() {
        if(!$this->T->notpl) {
            $this->_var->_SESSION = $_SESSION;
            $this->_var->_COOKIE = $_COOKIE;
            $cache_file = __X_APP_ROOT__.'/data/cache/tpl/' . __X_APP_DIRECTORY_NAME__ .$this->T->name.'.php';
            if($this->T->html2ajax == true) {
                ob_start();
            }
            include_once($cache_file);
            if($this->T->html2ajax == true) {
                $html = ob_get_contents();
                $this->ajax_return_json['html'] = $html;
                ob_clean();
            }
        }
        if(!empty($this->ajax_return_json)) {
            die(json_encode($this->ajax_return_json));
        }
    }
    public function fetch_templete() {
        if(empty($this->T->name)) {
            $this->T->notpl = true;
            $this->T->noecho = true;
        }
        if($this->T->notpl == false && !file_exists(__X_APP_ROOT__.'/theme/'.__X_APP_DIRECTORY_NAME__.$this->T->name.'.htm')) {
            throw new __X_DEBUG__('Theme File '.__X_APP_ROOT__.'/theme/'.__X_APP_DIRECTORY_NAME__.$this->T->name.'.htm not exists');
        }
        if(isset($this->T->echotype) && strtolower($this->T->echotype) == 'json') {
            $this->T->notpl = true;
        }
        if(isset($this->T->noecho) && $this->T->noecho === true) {
            $this->T->notpl = true;
        }
        if(isset($this->T->notpl) && $this->T->notpl === true) {
            return;
        } else {
            $tpl_file = __X_APP_ROOT__.'/theme/'.__X_APP_DIRECTORY_NAME__.$this->T->name.'.htm';
            $comp_file = __X_APP_ROOT__.'/data/cache/tpl/'.__X_APP_DIRECTORY_NAME__.$this->T->name.'.php';
            if(file_exists($comp_file)) {
                $comp_file_time = filemtime($comp_file);
            } else {
                $comp_file_time = 0;
            }
            if(file_exists($tpl_file)) {
                $guess_path_time = filemtime($tpl_file);
            } else {
                $guess_path_time = 0;
                throw new __X_DEBUG__('The Template File '.$tpl_file.' not exists');
            }
            if(!file_exists($comp_file)) {
                amkdir(dirname($comp_file));
            }
            if($comp_file_time <= $guess_path_time) {
                $this->parse_tpl($tpl_file, $comp_file);
            }
        }
    }
    public function inc_tpl($tpl) {
        $this->T->name = $tpl;
        $this->fetch_templete();
        $cache_file = __X_APP_ROOT__.'/data/cache/tpl/' . __X_APP_DIRECTORY_NAME__ . $this->T->name.'.php';
        include_once($cache_file);
    }
    public function parse_tpl($tpl_file,$comp_file) {
        $file_str = file_get_contents($tpl_file);
        $file_str = $this->parse_var($file_str);
        $file_str = $this->echo_value($file_str);
        $file_str = preg_replace('/\{inc\s+([a-zA-Z0-9_]+)\}/i','<?php $this->inc_tpl("$1");?>',$file_str);
        $file_str = $this->call_func($file_str);
        $file_str = $this->parse_if($file_str);
        $file_str = $this->parse_foreach($file_str);
        $file_str = $this->parse_set($file_str);
        $file_str = $this->parse_url($file_str);
        if(isset($this->cfg->html_zip) && $this->cfg->html_zip) {
            $file_str = $this->del_html_comment($file_str);
            $file_str = preg_replace('/[\n\t\r]+/i','',$file_str);
        }
        file_put_contents($comp_file, $file_str);
    }
    public function parse_foreach($str) {
        $str = preg_replace('/\{foreach\s+(\$\S+)\s+as(.*)\}/','<?php if(is_array($1) && !empty($1)){ foreach($1 as $2) { ?>',$str);
        return str_replace('{/foreach}','<?php }} ?>',$str);
    }
    public function del_html_comment($str) {
        return preg_replace('/<!--.*-->/i','',$str);
    }
    public function parse_set($str) {
        return preg_replace('/\{set\s+([^\{^\}]+)}/i','<?php $1;?>',$str);
    }
    //解析if else 结构
    public function parse_if($str) {
        $str = preg_replace('/\{if\s+([^\{^\}]+)\}/i','<?php if($1) { ?>',$str);
        $str = preg_replace('/\{elseif\s+([^\}\{]+)\}/i','<?php } elseif($1){?>', $str);
        $str = str_replace('{else}','<?php } else { ?>',$str);
        $str = str_replace('{/if}','<?php } ?>',$str);
        return $str;
    }
    //将变量进行转换
    public function parse_var ($str) {
        $str = preg_replace('/\$([a-zA-Z_]\w*)\.(\w+)\.([\w]+)/i', '\$$1[\'$2\'][\'$3\']',$str);
        $str = preg_replace('/\$([a-zA-Z_]\w*)\.(\w+)/i', '\$$1[\'$2\']',$str);
        return preg_replace('/\$([A-Za-z_]\w*)/i','\$this->_var->$1',$str);
    }
    public function parse_url($str) {
        return preg_replace_callback('/\{url=(\w+)\|{0,1}(\w*)\|{0,1}(.*)\}/i',
                function($match) {
                    $f = preg_replace('/(\$this->_var->[A-Za-z_]\w*)/i','{$1}',$match[1]);
                    $s = preg_replace('/(\$this->_var->[A-Za-z_]\w*)/i','{$1}',$match[2]);
                    $t = preg_replace('/(\$this->_var->[A-Za-z_][\w\[\'\]]*)/i','{$1}',$match[3]);
                    return "<?php \$this->echo_url(\"$f\",\"$s\",\"$t\")?>";
                },$str);
    }
    public function echo_url($cls, $method='', $params = '') {
        echo support_url_mode($cls,$method,$params,$this->cfg->uri_mode);
    }
    //解析所有可输出变量
    public function echo_value($str) {
        return preg_replace('/\{\$([a-zA-Z_][^\}\{]+)\}/i','<?php echo \$$1;?>',$str);
    }
    //调用函数
    public function call_func($str) {
        return preg_replace('/\{func\s+([a-zA-Z_\d]+)\((.*)\)\}/i','<?php if(function_exists(\'$1\')){echo $1($2);} elseif(method_exists($this,\'$1\')) {
                echo $this->$1($2);}?>',$str);
    }
    public function show_page_num() {
        echo '<div class="PageNum"><span>共计'.$this->T->record_num.'条记录</span><span>共计'.$this->T->page_num.'页</span>';
        if($this->T->current <= 5) {
            $start = 1;
        } else {
            $start = $this->T->current -5;
        }
        if($this->T->page_num <=5) {
            $max = $this->T->page_num +1;
        } elseif($this->T->page_num > $this->T->current +5) {
            $max = $this->T->current +5;
        } else {
            $max = $this->T->page_num;
        }
        for($i=$start;$i<$max;$i++) {
            if($i == $this->T->current) {
            echo "<span class=\"current\">$i</span>";
            } else {
                $vist_path = '';
                if(isset($_GET['c'])) {
                    $cls = $_GET['c'];
                    unset($_GET['c']);
                }
                if(isset($GET['m'])) {
                    $m = $_GET['m'];
                    unset($_GET['m']);
                } else {
                    $m = '';
                }
                $_GET['p'] = $i;
                $params = implode('&',$_GET);
                $url = support_url_mode($cls,$m,$params,$this->cfg->uri_mode);
                echo "<span><a href=\"{$url}\">$i</a></span>";
            }
        }
        echo '</div>';
    }
    public function __destruct() {
        //$this->create_static($this->global_data); 
    }
    public function create_static($global_data = null) {
        if(isset($global_data['cache_file'])) {
            if(!$this->cache_id) {
                ob_start();
                $this->cache_id = $global_data['cache_id'];
            } else {
                $str = ob_get_contents();
                ob_clean();
                file_put_contents(__X_APP_ROOT__ .'/'.  $this->cfg['cache_path'] .'/' . $global_data['cache_file']);
                $this->cache_id = false;
           }
       }
    }
}
